﻿var message=$('<div class="msgBox">' +
					'<form><h2></h2>' +
						'<div class="userinput"></div>' +
						'<div><textarea class="conBox f-text"></textarea></div>' +
						'<div class="tr">' +
							'<p><span class="countTxt">还能输入</span><strong class="maxNum">255</strong><span>个字</span>' +
								'<input class="sendBtn button grey" type="button" value="发 送"/>' +
							'</p>' +
						'</div>' +
					'</form>' +
					'<div class="last"></div>' +
				'</div>');

$(function(){
	
});
	/*
	 	动态显示还剩余几个字
	 */
function addListener1(obj){
	obj.find(".conBox").keyup(function(){
		var content=$(this).val();
		var temp=judeg(content);
		var num=255-temp;
		num=num-(content.length-temp);
		$(this).parents(".msgBox").find(".maxNum").text(num);
	});
	/*
		点击事件，封装json，传后台
	 */
	obj.find(".sendBtn").click(function(){
		var conBox=$(this).parents(".msgBox").find(".conBox");
		var letter={};
		letter.readerUser={};
		letter.readerUser.userId=$(this).parents(".msgBox").find("[type=hidden]").val();
		letter.content=conBox.val();
        $.post("sendLetter",{"letter":JSON.stringify(letter)},function(data){
			if(data>0){
				conBox.parents(".msgBox").find(".last").text(conBox.val());
				conBox.val("");
			}
		});
	});
}

function judeg(content){
	 var regex= /[\u4E00-\u9FA5]/g;
	 var result=0;
	 if (regex.test(content)){
		 result=content.match(regex).length;
	 }
	 return result;
}

function leavMessage(obj,userName,userId){
	var temp=$(obj).parents(".user_card");
	var msgBox=temp.find(".msgBox");
	if(msgBox.prop("class")!='msgBox'){
		var target=message.clone(false);
		target.find(".userinput").html('<input class="userName f-text" value="'+userName+'" disabled="true"/><input type="hidden" value="'+userId+'"/>');
		addListener1(target);
		temp.append(target);
		$(obj).text("关闭留言");
	}else{
		msgBox.remove();
		$(obj).text("留 言");
	}
}